﻿using OfficeOpenXml;
using System.Collections.Concurrent;
using System.IO;
using System.Windows.Media.Imaging;
using Image = System.Windows.Controls.Image;


namespace WPF_Preview.PreviewClass
{
    public class CustomWorksheet
    {
        public string Name { get; set; }
        public Dictionary<(int, int), string> Cells { get; set; }
        public int MaxRow { get; set; }
        public int MaxColumn { get; set; }
    }
    public class ExcelPreViewTool
    {
        private static WorksheetRenderer worksheetRenderer = new WorksheetRenderer();
        /// <summary>
        /// 读取整个Excel文件
        /// </summary>
        /// <param name="fileName">excel文件路径</param>
        /// <param name="plcVals">页，行，列，值</param>
        /// <param name="imageWindowManager">图像窗口管理器</param>
        /// <returns>从Excel文件中读取的单元格数据列表</returns>
        public static async Task<List<(int, int, int, string)>> ReadExcelAsync(string fileName, List<(int, int, int, string)> plcVals, ImageWindowManager imageWindowManager)
        {
            var result = new List<(int, int, int, string)>();
            if (string.IsNullOrEmpty(fileName))
            {
                return result;
            }
            try
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                // 后台线程执行文件读取和数据处理
                var data = await Task.Run(() =>
                {
                    using (var package = new ExcelPackage(new FileInfo(fileName)))
                    {
                        var worksheets = package.Workbook.Worksheets;
                        var cells = new List<(int, int)>();
                        var actions = new List<(BitmapSource, string)>();
                        var customWorksheets = new List<CustomWorksheet>();
                        for (int i = 0; i < worksheets.Count; i++)
                        {
                            var worksheet = worksheets[i];
                            if (plcVals.Count != 0 && plcVals.Any(x => x.Item1 == i + 1))
                            {
                                var currentSheet = plcVals.Where(x => x.Item1 == i + 1);
                                foreach (var item in currentSheet)
                                {
                                    try
                                    {
                                        var match = worksheet.Cells[item.Item2, item.Item3];
                                        if (match.ToString() != item.Item4)
                                        {
                                            worksheet.SetValue(item.Item2, item.Item3, match + $"/{item.Item4}");
                                            cells.Add((item.Item2, item.Item3));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        // 记录详细异常日志
                                        System.Diagnostics.Debug.WriteLine($"Error updating cell in worksheet {worksheet.Name}: {ex.Message}");
                                    }
                                }
                            }
                            try
                            {
                                var bitmap = worksheetRenderer.RenderWorksheetToBitmap(worksheet, cells);
                                var bitmapSource = worksheetRenderer.BitmapToBitmapSource(bitmap);
                                actions.Add((bitmapSource, worksheet.Name));
                            }
                            catch (Exception ex)
                            {
                                // 记录详细异常日志
                                System.Diagnostics.Debug.WriteLine($"Error rendering worksheet {worksheet.Name}: {ex.Message}");
                            }
                            // 遍历当前工作表的所有单元格，将数据添加到结果列表中
                            var dimension = worksheet.Dimension;
                            var customCells = new Dictionary<(int, int), string>();
                            int maxRow = 0;
                            int maxColumn = 0;
                            {
                                if (dimension != null)
                                {
                                    // 直接使用维度信息获取最大行列
                                    maxRow = dimension.End.Row;
                                    maxColumn = dimension.End.Column;
                                    foreach (var cell in worksheet.Cells)
                                    {
                                        int row = cell.Start.Row;
                                        int col = cell.Start.Column;
                                        string text = cell.Text;

                                        if (!string.IsNullOrEmpty(text))
                                        {
                                            result.Add((i + 1, row, col, text));
                                            customCells[(row, col)] = text;
                                        }
                                    }
                                    customWorksheets.Add(new CustomWorksheet
                                    {
                                        Name = worksheet.Name,
                                        Cells = customCells,
                                        MaxRow = maxRow,
                                        MaxColumn = maxColumn
                                    });
                                }
                            }
                        }
                        return (actions, result, customWorksheets);
                    }
                });
                // 回到 UI 线程更新 UI
                await System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    var ordered = data.Item1.OrderBy(x => x.Item2).ToArray();
                    var images = new List<Image>();
                    var sheetNames = new List<string>();

                    for (int i = 0; i < ordered.Length; i++)
                    {
                        var img = new Image { Source = ordered[i].Item1 };
                        images.Add(img);
                        sheetNames.Add(ordered[i].Item2);
                    }
                    imageWindowManager.ShowImageInNewWindow(fileName, images, sheetNames, data.Item3);
                }));
                return data.Item2;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"操作失败: {ex.Message}");
                return result;
            }
        }
    }
}
